package cn.hsw.platform.controller;

import cn.hsw.platform.contants.ManageConstant;
import cn.hsw.platform.core.doc.annotation.AuthPermission;
import cn.hsw.platform.core.base.BaseServiceController;
import cn.hsw.platform.core.dto.ResultDto;
import cn.hsw.platform.core.util.BeanUtil;
import cn.hsw.platform.core.util.ResultUtil;
import cn.hsw.platform.core.util.Validator;
import cn.hsw.platform.dto.MenuDto;
import cn.hsw.platform.model.PermissionModel;
import cn.hsw.platform.service.PermissionService;
import cn.hsw.platform.vo.PermissionVO;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 权限 code
 * @author 李子木
 * @date 2020-11-04
 */
@RestController
@RequestMapping("/permission")
public class PermissionController extends BaseServiceController<PermissionService> {

    /**
     * 权限新增
     * @param permissionVO 对象
     * @return 接口返回
     */
    @PostMapping("/add")
    @AuthPermission("manage:permission:add")
    public ResultDto<Object> add(@Validated PermissionVO permissionVO){

        /*验证不通类型的参数*/
        checkType(permissionVO.getType(),permissionVO.getParentPid());

        PermissionModel permissionModel = BeanUtil.copyProperties(permissionVO, PermissionModel.class);
        service.save(permissionModel);


        return ResultUtil.success();
    }

    /**
     * 权限删除
     * @param permissionModel 要删除的对象
     * @return 接口返回
     */
    @PostMapping("/del/{pid}")
    @AuthPermission("manage:permission:del")
    public ResultDto<Object> del(@PathVariable("pid")PermissionModel permissionModel){

        Validator.validateNotNull(permissionModel,"不存在或已删除");

        service.delete(permissionModel);

        return ResultUtil.success();
    }

    /**
     * 权限修改
     * @param permissionModel 要修改的对象
     * @param permissionVO 要修改的内容
     * @return 接口返回
     */
    @PostMapping("/edit/{pid}")
    @AuthPermission("manage:permission:edit")
    public ResultDto<Object> edit(@PathVariable("pid")PermissionModel permissionModel,PermissionVO permissionVO){

        Validator.validateNotNull(permissionModel,"不存在或已删除");

        /*验证不通类型的参数*/
        checkType(permissionModel.getType(),permissionVO.getParentPid());
        permissionModel.setParentPid(permissionVO.getParentPid());

        service.edit(permissionModel,permissionVO);

        return ResultUtil.success();
    }

    /**
     * 权限显示状态修改
     * @param permissionModel 要修改的对象
     * @param state 1 显示 -1不显示
     * @return 接口返回
     */
    @PostMapping("/edit/state/{pid}")
    @AuthPermission("manage:permission:edit:state")
    public ResultDto<Object> editState(@PathVariable("pid")PermissionModel permissionModel,@RequestParam(name = "state")Integer state){

        Validator.validateNotNull(permissionModel,"不存在或已删除");
        Validator.validateContains(new String[]{ManageConstant.PERMISSION_STATE_SHOW+"",ManageConstant.PERMISSION_STATE_NOT_SHOW+""}
                ,state+"","状态必须是"+ManageConstant.PERMISSION_STATE_SHOW+ManageConstant.PERMISSION_STATE_NOT_SHOW);
        permissionModel.setState(state);

        service.save(permissionModel);

        /* @TODO 权限信息变更，删除权限缓存*/

        return ResultUtil.success();
    }


    /**
     * 权限列表树
     * @return 列表树
     */
    @PostMapping("/tree")
    @AuthPermission("manage:permission:tree")
    public ResultDto<Object> tree(@RequestParam(name = "type",defaultValue = ManageConstant.PERMISSION_TYPE_API+"")int type){
        List<PermissionModel> list = service.findByParentPidNull();
        switch (type){
            case ManageConstant.PERMISSION_TYPE_MENU:
                checkMenuList(list);
                break;
            case ManageConstant.PERMISSION_TYPE_PAGE:
                checkPageList(list);
                break;
            default:
        }
        return ResultUtil.success(list);
    }

    /**
     * 权限列表树
     * @return 列表树
     */
    @PostMapping("/menu")
    @AuthPermission("manage:permission:menu")
    public ResultDto<Object> tree(){

        MenuDto menu = service.menu(11004266282115072L);

        return ResultUtil.success(menu);
    }


    /**
     * 权限列表
     * @return 列表
     */
    @Deprecated
    @PostMapping("/list")
    @AuthPermission("manage:permission:list")
    public ResultDto<Object> list(){

        List<PermissionModel> list = service.findAll();

        for (PermissionModel model:list){
            model.setPermissionModelList(null);
        }

        return ResultUtil.success(list);
    }

    /**
     * 权限详情
     * @return 详情
     */
    @Deprecated
    @PostMapping("/info/{pid}")
    @AuthPermission("manage:permission:info")
    public ResultDto<Object> info(@PathVariable("pid")PermissionModel permissionModel){

        permissionModel.setPermissionModelList(null);

        if(Validator.isNotEmpty(permissionModel.getParentPid())){
            PermissionModel parentPermissionModel = service.findById(permissionModel.getParentPid());
            permissionModel.setParentInfo(permissionModel.getParentPermission(permissionModel.getParentPid(),parentPermissionModel.getName()));
        }

        return ResultUtil.success(permissionModel);
    }


    /**
     * 不同类型下的值验证
     * @param type 类型
     * @param parentPid 父ID
     */
    private void checkType(int type,Long parentPid){
        switch (type){
            case ManageConstant.PERMISSION_TYPE_MENU:

                break;
            case ManageConstant.PERMISSION_TYPE_PAGE:
                Validator.validateNotEmpty(parentPid,"页面必须在菜单下");
                Validator.validateEqual(ManageConstant.PERMISSION_TYPE_MENU,service.findById(parentPid).getType(),"页面必须在菜单下");
                break;
            case ManageConstant.PERMISSION_TYPE_API:
                Validator.validateNotEmpty(parentPid,"功能必须在页面下");
                Validator.validateEqual(ManageConstant.PERMISSION_TYPE_PAGE,service.findById(parentPid).getType(),"功能必须在页面下");
                break;
            default:

        }
    }

    private void checkMenuList(List<PermissionModel> list){
        List<PermissionModel> delList = new ArrayList<>();
        list.forEach(permissionModel -> {
            //如果这个不是菜单 干掉
            if(permissionModel.getType() == ManageConstant.PERMISSION_TYPE_MENU){
                if(permissionModel.getPermissionModelList().size()>0){
                    checkMenuList(permissionModel.getPermissionModelList());
                }
            }else{
                delList.add(permissionModel);
            }
        });
        list.removeAll(delList);
    }
    private void checkPageList(List<PermissionModel> list){
        List<PermissionModel> delList = new ArrayList<>();
        list.forEach(permissionModel -> {
            //如果这个不是菜单 干掉
            if(permissionModel.getType() == ManageConstant.PERMISSION_TYPE_MENU||permissionModel.getType() == ManageConstant.PERMISSION_TYPE_PAGE){
                if(permissionModel.getPermissionModelList().size()>0){
                    checkPageList(permissionModel.getPermissionModelList());
                }
            }else{
                delList.add(permissionModel);
            }
        });
        list.removeAll(delList);
    }

}
